import React from 'react';
import { View, Alert, Linking, Platform, StyleSheet } from 'react-native';
import { WebView } from 'react-native-webview';

export default function AlipayWebView({ route, navigation }) {
  const { html } = route.params;

  // 统一处理跳转
  const handleUrl = (url) => {
    console.log('WebView尝试加载:', url);
    // 支付完成回调
    if (url.startsWith('echioh://pay/result')) {
      // 这里可以解析参数，做更多处理
      Alert.alert('支付完成', '即将返回首页');
      // 返回首页
      navigation.navigate('MainTabs');
      return false;
    }
    // 拦截所有非 http/https/about:blank 的 scheme
    if (
      !url.startsWith('http') &&
      !url.startsWith('https') &&
      !url.startsWith('about:blank')
    ) {
      Linking.openURL(url).catch(() => {
        Alert.alert('无法打开支付App', '请确认已安装相关App');
      });
      return false;
    }
    return true;
  };

  return (
    <View style={{ flex: 1 }}>
      <WebView
        originWhitelist={['*']}
        source={{ html }}
        javaScriptEnabled
        domStorageEnabled
        startInLoadingState
        style={{ flex: 1 }}
        mixedContentMode="always"
        onShouldStartLoadWithRequest={event => handleUrl(event.url)}
        onNavigationStateChange={event => {
          if (Platform.OS === 'ios') {
            handleUrl(event.url);
          }
        }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  webview: {
    flex: 1,
  },
});